Passing mix of T and T[] to a Java varargs method

Posted by rfalke on Stack Overflow See other posts from Stack Overflow or by rfalke
Published on 2010-05-13T19:48:11Z Indexed on 2010/05/13 19:54 UTC
Read the original article Hit count: 187

Filed under:
|

Suppose you have a Java method

void foobar(int id, String ... args)

and want to pass both String arrays and Strings into the method. Like this

String arr1[]={"adas", "adasda"};
String arr2[]={"adas", "adasda"};
foobar(0, "adsa", "asdas");
foobar(1, arr1);
foobar(2, arr1, arr2);
foobar(3, arr1, "asdas", arr2);

In Python there is "*" for this. Is there some way better than such rather ugly helper method:

static String[] concat(Object... args) {
    List<String> result = new ArrayList<String>();
    for (Object arg : args) {
        if (arg instanceof String) {
            String s = (String) arg;
            result.add(s);
        } else if (arg.getClass().isArray() && arg.getClass().getComponentType().equals(String.class)) {
            String arr[] = (String[]) arg;
            for (String s : arr) {
                result.add(s);
            }
        } else {
            throw new RuntimeException();
        }
    }
    return result.toArray(new String[result.size()]);
}

which allows

foobar(4, concat(arr1, "asdas", arr2));

© Stack Overflow or respective owner

Related posts about java

Related posts about varargs